package com.example.demo.util;

import java.io.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 初始化敏感词库，将敏感词加入到HashMap中，构建DFA算法模型
 */
public class SensitiveWordInit {

    public HashMap sensitiveWordMap;


    public Map initKeyWord(String path) {
        try {
            //读取敏感词库
            Set<String> keyWordSet = readSensitiveWordFile(path);
            //将敏感词库加入到HashMap中
            addSensitiveWordToHashMap(keyWordSet);
            //spring获取application，然后application.setAttribute("sensitiveWordMap",sensitiveWordMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sensitiveWordMap;
    }

    /**
     * 读取敏感词库，将敏感词放入HashSet中，构建一个DFA算法模型：<br>
     *
     * @param keyWord 敏感词库
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    private void addSensitiveWordToHashMap(Set<String> keyWord) {
        sensitiveWordMap = new HashMap(keyWord.size());
        // 当前正在处理的敏感词
        String key = null;
        // 当前的map
        Map nowMap = null;
        Map<String, String> newWorMap = null;
        //迭代keyWordSet
        Iterator<String> iterator = keyWord.iterator();
        while (iterator.hasNext()) {
            key = iterator.next();    //关键字
            nowMap = sensitiveWordMap;
            for (int i = 0,length = key.length(); i < length; i++) {
                /*
                        中国人：
                            K:中，V:HashMap,(isEnd=0)
                                    |
                                    |
                                    V
                                    K:国,V:HashMap,(isEnd=0)
                                            |
                                            |
                                            V
                                            K:人,V:,(isEnd=1)
                 */
                char keyChar = key.charAt(i);//转换成char型
                Object wordMap = nowMap.get(keyChar);//获取
                if (wordMap != null) {//如果存在该key，直接赋值
                    nowMap = (Map) wordMap;
                } else {     //不存在则，则构建一个map，同时将isEnd设置为0，因为他不是最后一个
                    newWorMap = new HashMap<>();
                    newWorMap.put("isEnd", "0");     //0表示不是最后一个
                    nowMap.put(keyChar, newWorMap);
                    nowMap = newWorMap;
                }
                if (i == key.length() - 1) {
                    nowMap.put("isEnd", "1");    //最后一个
                }
            }
        }
    }

    /**
     * 读取敏感词库中的内容，将内容添加到set集合中
     */
    private Set<String> readSensitiveWordFile(String filePath) {
        Set<String> set = new HashSet<>();
        //读取文件
        File file = new File(filePath);
        // 如果文件不存在或者是文件夹就直接返回一个空的集合
        if (!file.exists() || file.isDirectory()) {
            return set;
        }
        String txt;
        InputStreamReader read = null;
        BufferedReader bufferedReader = null;
        try {
            read = new InputStreamReader(new FileInputStream(file));
            bufferedReader = new BufferedReader(read);
            //读取文件，将文件内容放入到set中
            while ((txt = bufferedReader.readLine()) != null) {
                set.add(txt);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(read);
            close(bufferedReader);

        }
        return set;
    }

    /**
     * 关流
     */
    private void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {

            }
        }
    }
}